<?php

namespace app\traits;


use app\model\Activity;
use app\model\ActivityPromotionEffect;
use app\model\DyGoodsOrder;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;

trait SyncGoodsEffectTrait
{
    //获取推广效果
    public function getPromotionEffect($activityId)
    {
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/goods?id=" . $activityId . "&tabActiveKey=2";
        $requestUrl = "https://buyin.jinritemai.com/api/common/promotion/effect";
        $page = 1;
        $finish = false;
        $activityUpdated = false;
        do {
            $payload = [
                'activity_id' => $activityId,
                'page' => 1,
                'pageSize' => 100,
                'page_size' => 100
            ];
            $headers = [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
                'Referer' => $referUrl
            ];
            $client = new Client();
            $cookies = config('app.buyin');
            try {
                $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
                // debug 'debug'=>true
                $response = $client->request('GET', $requestUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
            } catch (\Exception $e) {
                Log::info($e->getMessage());
                return ['code' => -1, 'msg' => $e->getMessage()];
            }
            $result = json_decode($response->getBody()->getContents(), true);
            if(!$result){
                return ['code' => -9, 'msg' => '巨浪百应账号登录已过期'];
            }
            if ($result['code'] == 0) {
                if (!$activityUpdated) {
                    Activity::where(['buyin_activity_id' => $activityId])
                        ->update([
                            'promote_product_num' => $result['promote_product_num'],
                            'order_pay_num' => $result['order_pay_num'],
                            'order_pay_amount' => $result['order_pay_amount'],
                            'estimated_service_fee' => $result['estimated_service_fee']
                        ]);
                    $activityUpdated = true;
                }
                if ($result['total'] > 0) {
                    foreach ($result['data'] as $k2 => $v2) {
                        $exist = ActivityPromotionEffect::where(['buyin_activity_id' => $activityId, 'product_id' => $v2['product_id']])->findOrEmpty();
                        if ($exist->isEmpty()) {
                            $promotionEffect = [
                                'buyin_activity_id' => $activityId,
                                'product_id' => $v2['product_id'],
                                'product_name' => $v2['product_name'],
                                'product_img' => $v2['product_img'],
                                'product_price' => $v2['product_price'],
                                'service_rate' => $v2['service_rate'],
                                'commission_rate' => $v2['commission_rate'],
                                'order_pay_num' => $v2['order_pay_num'],
                                'order_pay_amount' => $v2['order_pay_amount'],
                                'estimated_service_fee' => $v2['estimated_service_fee'],
                                'estimated_commission_fee' => $v2['estimated_commission_fee'],
                                'create_time' => date('Y-m-d H:i:s', time()),
                                'update_time' => date('Y-m-d H:i:s', time())
                            ];
                            ActivityPromotionEffect::create($promotionEffect);
                        } else {
                            $promotionEffect = [
                                'service_rate' => $v2['service_rate'],
                                'commission_rate' => $v2['commission_rate'],
                                'order_pay_num' => $v2['order_pay_num'],
                                'order_pay_amount' => $v2['order_pay_amount'],
                                'estimated_service_fee' => $v2['estimated_service_fee'],
                                'estimated_commission_fee' => $v2['estimated_commission_fee'],
                                'update_time' => date('Y-m-d H:i:s', time())
                            ];
                            ActivityPromotionEffect::where(['buyin_activity_id' => $activityId, 'product_id' => $v2['product_id']])->update($promotionEffect);
                        }
                    }
                }
            } else {
                return ['code' => -1, 'msg' => $result['msg']];
            }
            $totalPage = ceil($result['total'] / 50);
            $page++;
            // 当前页数 > 总页数
            if ($page > $totalPage) {
                $finish = true;
            }
        } while (!$finish);

        return ['code' => 1, 'msg' => 'success', 'data' => $result];
    }

    //获取服务费明细(即订单)
    public function getServiceFeeList($productId)
    {
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/serviceCharge?productId=" . $productId;
        $requestUrl = "https://buyin.jinritemai.com/api/common/service/fee/list";
        $page = 1;
        $finish = false;
        do{
            //查询90天内的订单
            $payload = [
                'start_time'=> Carbon::now()->subDays(89)->toDateTimeString(),
                'end_time'=>date('Y-m-d H:i:s',time()),
                'order_status'=>0,
                'product_id'=>$productId,
                'search_type'=>'pay',
                'page'=>$page,
                'pageSize'=>20,
                'page_size'=>20
            ];
            $headers = [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
                'Referer' => $referUrl
            ];
            $client = new Client();
            $cookies = config('app.buyin');
            try {
                $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
                $response = $client->request('GET', $requestUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
            } catch (\Exception $e) {
                return ['code' => -1, 'msg' => $e->getMessage()];
            }
            $result = json_decode($response->getBody()->getContents(), true);
            if(!$result){
                return ['code' => -9, 'msg' => '巨浪百应账号登录已过期'];
            }
            if ($result['code'] == 0) {
                if ($result['total'] > 0) {
                    foreach ($result['data'] as $k2 => $v2) {
                        $orderExist = DyGoodsOrder::where(['product_id'=>$v2['product_id'],'order_id'=>$v2['order_id']])->findOrEmpty();
                        if($orderExist->isEmpty()){
                            $order = [
                                'order_id'=>$v2['order_id'],
                                'product_id'=>$v2['product_id'],
                                'product_name'=>$v2['product_name'],
                                'product_img'=>$v2['product_img'],
                                'flow_point'=>$v2['flow_point'],
                                'author_name'=>$v2['author_name'],
                                'pay_amount'=>$v2['pay_amount'],
                                'pay_succ_time'=>$v2['pay_succ_time'],
                                'service_rate'=>$v2['service_rate'],
                                'estimated_service_fee'=>$v2['estimated_service_fee'],
                                'real_service_fee'=>$v2['real_service_fee'],
                                'settle_time'=>$v2['settle_time'],
                                'stage_one_pay_money'=>$v2['stage_one_pay_money'],
                                'stage_one_pay_time'=>$v2['stage_one_pay_time'],
                                'stage_order'=>$v2['stage_order'],
                                'stage_two_pay_time'=>$v2['stage_two_pay_time'],
                                'create_time'=>date('Y-m-d H:i:s', time()),
                                'update_time'=>date('Y-m-d H:i:s', time())
                            ];
                            DyGoodsOrder::create($order);
                        }else{
                            $order = [
                                'flow_point'=>$v2['flow_point'],
                                'author_name'=>$v2['author_name'],
                                'pay_amount'=>$v2['pay_amount'],
                                'pay_succ_time'=>$v2['pay_succ_time'],
                                'service_rate'=>$v2['service_rate'],
                                'estimated_service_fee'=>$v2['estimated_service_fee'],
                                'real_service_fee'=>$v2['real_service_fee'],
                                'settle_time'=>$v2['settle_time'],
                                'stage_one_pay_money'=>$v2['stage_one_pay_money'],
                                'stage_one_pay_time'=>$v2['stage_one_pay_time'],
                                'stage_order'=>$v2['stage_order'],
                                'stage_two_pay_time'=>$v2['stage_two_pay_time'],
                                'update_time'=>date('Y-m-d H:i:s', time())
                            ];
                            DyGoodsOrder::where(['product_id'=>$v2['product_id'],'order_id'=>$v2['order_id']])->update($order);
                        }
                    }
                }
            } else {
                return ['code' => -1, 'msg' => $result['msg']];
            }
            $totalPage = ceil($result['total'] / 20);
            $page++;
            // 当前页数 > 总页数
            if ($page > $totalPage) {
                $finish = true;
            }
        }while(!$finish);

        return ['code' => 1, 'msg' => 'success', 'data' => $result];
    }

}